<template>
  <div class="hello">
    <h1>{{ msg2 }}</h1>
  </div>
  <div>counter: {{ counter }}</div>
  <div>doubleCounter: {{ dc }}</div>
  <p ref="desc"></p>
  <div id="globalApi"></div>

  <!-- Teleport -->
  <ModalWindow></ModalWindow>

  <!-- emit -->
  <Emit @click="onClick" />

  <!-- main.js中声明的全局组件 -->
  <comp />

  <!-- V-modal -->
  <VModalTest v-model:counter="vmodal" />
  <!-- 等效于 -->
  <!-- <VModalTest :counter="vmodal" @update:counter="counter=$event" /> -->

  <!-- 渲染API -->
  <RenderAPI />
</template>

<script>
import { computed, reactive, ref, toRefs } from '@vue/reactivity'
import { onMounted, onUnmounted, watch } from '@vue/runtime-core';
import ModalWindow from './ModalWindow.vue'
import Emit from './Emit.vue'
import RenderAPI from './RenderAPI.vue'
import VModalTest from './VModalTest.vue'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },

  data () {
    return {
      vmodal: 1
    }
  },

  setup () {
    const { counter, dc } = count();
    const msg2 = ref('this is a test')

    // 使用元素的引用
    const desc = ref(null)
    // 监听
    watch(counter, (n, o) => {
      // 这个就是p元素
      const p = desc.value
      p.textContent = `old ${o} to new ${n}`
    })
    return { counter, dc, msg2, desc }
  },

  components: {
    ModalWindow,
    Emit,
    RenderAPI,
    VModalTest,
  },

  methods: {
    onClick () {
      console.log('click event');
    }
  }
};

function count () {
  const data = reactive({
    counter: 1,
    dc: computed(() => data.counter * 2)
  })

  let timer;

  onMounted(() => {
    timer = setInterval(() => {
      data.counter++
    }, 1000)
  })

  onUnmounted(() => {
    clearInterval(timer);
    timer = null;
  })
  return toRefs(data)
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
